from sqlobject import *
from sqlobject.sqlbuilder import *

class Platform(SQLObject):
	name = UnicodeCol(notNone = True, alternateID = True)
	shortName = UnicodeCol(default = None)

	games = SQLMultipleJoin("Game", joinColumn="platform", orderBy="name")

class Game(SQLObject):
	name = UnicodeCol(notNone = True)
	platform = ForeignKey("Platform", notNone = True)
	releaseDate = DateCol(default = None)
	icon = BLOBCol(default = None)

	trophies = SQLMultipleJoin("Trophy", joinColumn="game", orderBy="trophy_order")

class Trophy(SQLObject):
	name = UnicodeCol(default = None)
	order = IntCol(notNone = True, dbName='trophy_order')
	type = UnicodeCol(notNone = True)
	game = ForeignKey("Game", notNone = True)
	description = UnicodeCol(default = None)
	icon = BLOBCol(default = None)
	date = UnicodeCol(default = None)
	obtained = BoolCol(notNone = True, default = False)
	hidden = BoolCol(notNone = True, default = False)

def init(uri = None):
	if not uri:
		import os
		CONFIG_FILE = os.path.join(os.environ['HOME'], '.wjs.ini')
		from ConfigParser import SafeConfigParser as ConfigParser
		config = ConfigParser()
		config.read(CONFIG_FILE)
		uri = config.get("dsn", "games")
	global connection
	connection = connectionForURI(uri)
	sqlhub.processConnection = connection
	Platform.createTable(ifNotExists = True)
	Game.createTable(ifNotExists = True)
	Trophy.createTable(ifNotExists = True)

def createPlatforms():
	Platform(name = 'PC')
	Platform(name = 'Playstation 3', shortName = 'PS3')
	Platform(name = 'Nintendo Wii', shortName = 'Wii')
	Platform(name = 'Nintendo DS', shortName = 'DS')
	Platform(name = 'Playstation Portable', shortName = 'PSP')
	Platform(name = 'Xbox 360', shortName = 'X360')

def enableFTS():
	connection.query("CREATE VIRTUAL TABLE game_names USING FTS3(tokenize=porter)")
	connection.query("INSERT INTO game_names (rowid, content) SELECT id, name FROM game")

def getFTSname(name):
	return list(connection.queryAll("SELECT rowid FROM game_names WHERE content MATCH %s" % connection.sqlrepr(name)))

def getFTSMatch(name):
	results = getFTSname(name)
	if results and len(results) == 1:
		return Game.get(results[0][0])

def disableFTS():
	connection.query("DROP TABLE game_names")

def getPlatform(name):
	try:
		return Platform.byName(name)
	except SQLObjectNotFound:
		return Platform.select(Platform.q.shortName == name).getOne()

def mergeGames(original, duplicate):
	if not original.platform and duplicate.platform:
		original.platform = duplicate.platform
	if not original.releaseDate and duplicate.releaseDate:
		original.releaseDate = duplicate.releaseDate
	if not original.icon and duplicate.icon:
		original.icon = duplicate.icon
	if original.trophies.count() == 0:
		trophies = list(duplicate.trophies)
		for trophy in trophies:
			trophy.game = original
	Game.delete(duplicate)


if __name__ == '__main__':
	init()
	createPlatforms()
	#~ createGameNamesDB()
